package org.eae.eldf.service.base.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.eae.eldf.dao.base.IBaseCompanyInfoDao;
import org.eae.eldf.dao.base.impl.BaseCompanyInfoDaoImpl;
import org.eae.eldf.dao.portal.IPortalCompanyRoleDao;
import org.eae.eldf.dao.portal.impl.PortalCompanyRoleDaoImpl;
import org.eae.eldf.dto.base.BaseCompanyInfoQueryDto;
import org.eae.eldf.entity.base.BaseCompanyInfo;
import org.eae.eldf.entity.company.PortalCompanyUser;
import org.eae.eldf.entity.company.PortalCompanyUserRole;
import org.eae.eldf.entity.module.ModuleCompany;
import org.eae.eldf.entity.module.ModuleInfo;
import org.eae.eldf.entity.module.ModuleRole;
import org.eae.eldf.entity.module.ModuleRolePurview;
import org.eae.eldf.entity.portal.PortalCompanyRole;
import org.eae.eldf.entity.portal.PortalCompanyRolePurview;
import org.eae.eldf.framework.pager.Pagination;
import org.eae.eldf.framework.persistence.Criteria;
import org.eae.eldf.framework.redis.ObjectRedisTemplate;
import org.eae.eldf.framework.service.BaseServiceImpl;
import org.eae.eldf.framework.spring.SpringSecurityUtils;
import org.eae.eldf.framework.utils.CommonConstant;
import org.eae.eldf.framework.utils.MD5;
import org.eae.eldf.framework.utils.CommonContants;
import org.eae.eldf.service.base.BaseCompanyInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BaseCompanyInfoServiceImpl extends BaseServiceImpl<BaseCompanyInfo> implements BaseCompanyInfoService{

	private IBaseCompanyInfoDao baseCompanyInfoDao;
	@Autowired
	public void setIBaseCompanyInfoDao(BaseCompanyInfoDaoImpl baseCompanyInfoDao) {
		this.baseCompanyInfoDao = baseCompanyInfoDao;
		this.dao = baseCompanyInfoDao;
	}
	
	private ObjectRedisTemplate objectRedisTemplate;
	
	private IPortalCompanyRoleDao portalCompanyRoleDao;
	
	@Autowired
	public void setPortalCompanyRoleDao(PortalCompanyRoleDaoImpl portalCompanyRoleDao) {
		this.portalCompanyRoleDao = portalCompanyRoleDao;
	}
	

	@Autowired
	public void setObjectRedisTemplate(ObjectRedisTemplate objectRedisTemplate) {
		this.objectRedisTemplate = objectRedisTemplate;
	}
	
	//查询所有baseCompanyInfo
	@Override
	public Pagination<BaseCompanyInfo> queryListBaseCompanyInfo(
			Pagination<BaseCompanyInfo> pager, BaseCompanyInfoQueryDto baseCompanyInfoQueryDto) {
		// TODO Auto-generated method stub
		 pager = baseCompanyInfoDao.queryListBaseCompanyInfo(pager, baseCompanyInfoQueryDto);
		 return pager;
	}
	//通过id查询
	@Override
	public BaseCompanyInfo findByBaseCompanyInfoId(Long id) {
		// TODO Auto-generated method stub
		return baseCompanyInfoDao.get(BaseCompanyInfo.class, id);
	}
	//通过id删除
	@Override
	public void deleteBaseCompanyInfo(Long id) {
		// TODO Auto-generated method stub
		baseCompanyInfoDao.delete(Criteria.create(BaseCompanyInfo.class).where("baseCompanyInfoId", new Object[]{id}));	
	}

	//reids加载企业信息
	@Override
	public void loadCompanyToRedis(){
		ValueOperations<String,Object> redisValueObj = objectRedisTemplate.opsForValue();
		List<BaseCompanyInfo>  list=baseCompanyInfoDao.queryCompanyList();
		for (BaseCompanyInfo baseCompanyInfo : list) {
			redisValueObj.set(CommonContants.CONPANYINFO+baseCompanyInfo.getCompanyCode(), baseCompanyInfo);
		}
		
	}
	
	/**
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2016-8-3
	 * @see org.eae.eldf.service.base.BaseCompanyInfoService#clearRedis(java.lang.String)
	**/
	@Override
	public void clearRedis(String companyCode) {
		List<String> redisKeys = new ArrayList<String>();
		//企业下拥有的模块和菜单
		
//		List<ModuleCompany> mcList = baseCompanyInfoDao.queryList(Criteria.create(ModuleCompany.class).where("companyCode", new Object[]{companyCode}));
		redisKeys.add(CommonConstant.REDIS_COMPANY_MODULE_LIST_KEY+companyCode);
		Set<String> keys1 = objectRedisTemplate.keys(CommonConstant.REDIS_MODULE_MENU_LIST_KEY+"*");
		for(String s : keys1){redisKeys.add(s);}
		Set<String> keys2 = objectRedisTemplate.keys(CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY+"*");
		for(String s : keys2){redisKeys.add(s);}
		Set<String> keys3 = objectRedisTemplate.keys(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY+"*");
		for(String s : keys3){redisKeys.add(s);}
		Set<String> keys4 = objectRedisTemplate.keys(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY_BY_MENU+"*");
		for(String s : keys4){redisKeys.add(s);}
		Set<String> keys5 = objectRedisTemplate.keys(CommonConstant.REDIS_PLATEFORM_TEMPLATE_ID+"*");
		for(String s : keys5){redisKeys.add(s);}
		Set<String> keys6 = objectRedisTemplate.keys(CommonConstant.REDIS_PLATEFORM_TABLE_CONDITION_LIST_TEMPLATEID+"*");
		for(String s : keys6){redisKeys.add(s);}
		Set<String> keys7 = objectRedisTemplate.keys(CommonConstant.REDIS_PLATEFORM_TABLE_VIEW_LIST_TEMPLATEID+"*");
		for(String s : keys7){redisKeys.add(s);}
		Set<String> keys8 = objectRedisTemplate.keys(CommonConstant.REDIS_PLATEFORM_TABLE_OP_LIST_CONDITIONID+"*");
		for(String s : keys8){redisKeys.add(s);}
		Set<String> keys10 = objectRedisTemplate.keys(CommonConstant.REDIS_PLATEFORM_TEMPLATE_SAVE_ID+"*");
		for(String s : keys10){redisKeys.add(s);}
		Set<String> keys13 = objectRedisTemplate.keys(CommonConstant.REDIS_PLATEFORM_TEMPLATE_CODE+"*");
		for(String s : keys13){redisKeys.add(s);}
		
//		redisKeys.add(CommonConstant.REDIS_MODULE_MENU_LIST_KEY+"_*");
		redisKeys.add(CommonConstant.REDIS_ALL_PURVIEW_PATHSET_KEY);
//		redisKeys.add(CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY+"_*");
//		redisKeys.add(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY+"_*");
//		redisKeys.add(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY_BY_MENU+"_*");
//		for(ModuleCompany info : mcList){
//			redisKeys.add(CommonConstant.REDIS_MODULE_MENU_LIST_KEY+"_"+info.getModuleInfoId());
//		}
		//企业下用户的角色资源等缓存
//		List<PortalCompanyUser> cuList = baseCompanyInfoDao.queryList(Criteria.create(PortalCompanyUser.class).where("companyCode", new Object[]{companyCode}));
//		for(PortalCompanyUser c : cuList){
//			redisKeys.add(CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY+c.getCompanyCode()+c.getUsername());
//			redisKeys.add(CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY+c.getCompanyCode()+c.getUsername());
//		}
		objectRedisTemplate.delete(redisKeys);
	}
	
	
	

	@Override
	public void createCompany(BaseCompanyInfo baseCompanyInfo) {
		// TODO Auto-generated method stub
//		String companyCode = baseCompanyInfoDao.executeProcGetCode("COMPANY_CODE","system");
		String companyCode = baseCompanyInfo.getCompanyCode();
		Criteria c = Criteria.create(BaseCompanyInfo.class).set("companyCode", companyCode)
				.set("companyName", baseCompanyInfo.getCompanyName())
				.set("companyNameKey", baseCompanyInfo.getCompanyNameKey())
				.set("companyAddr", baseCompanyInfo.getCompanyAddr())
				.set("companyRemark", baseCompanyInfo.getCompanyRemark())
				.set("companyScale", baseCompanyInfo.getCompanyScale())
				.set("isEnable", baseCompanyInfo.getIsEnable())
				.set("companyType", 2)
				.set("createUser", SpringSecurityUtils.getCurrentUserName())
				.set("exta", baseCompanyInfo.getExta())
				.set("extb", baseCompanyInfo.getExtb())
				.set("extc", baseCompanyInfo.getExtc())
				.set("extd", baseCompanyInfo.getExtd())
				.set("exte", baseCompanyInfo.getExte());
		baseCompanyInfoDao.insert(c);
		ValueOperations<String,Object> redisValueObj = objectRedisTemplate.opsForValue();
		redisValueObj.set(CommonContants.CONPANYINFO+baseCompanyInfo.getCompanyCode(), baseCompanyInfo);
		BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
		// 生成企业管理员账号 portal_company_user
		Criteria companyUser = Criteria
				.create(PortalCompanyUser.class)
				.set("username", baseCompanyInfo.getUsername())
				.set("email", baseCompanyInfo.getEmail())
				.set("state", baseCompanyInfo.getIsEnable())
				.set("lastUpdateTime", new Date())
				.set("companyCode", companyCode)
				.set("defaultUser", 1)
				.set("pwd", passwordEncoder.encode(baseCompanyInfo.getPassword()))
				.set("phone", baseCompanyInfo.getPhone());
		baseCompanyInfoDao.insert(companyUser);
		
		
		// 给企业分配默认模块
		List<ModuleInfo> listModuleInfo = baseCompanyInfoDao.queryList(Criteria.create(ModuleInfo.class).where("isDefault", new Object[]{1}));
		Object[] moduleInfoId = new Object[listModuleInfo.size()];
		for (int i = 0; i < listModuleInfo.size(); i++) {
			if(listModuleInfo.get(i)!=null){
				moduleInfoId[i] = listModuleInfo.get(i)
						.getModuleInfoId();
				Criteria criteriaModuleCompany = Criteria
						.create(ModuleCompany.class)
						.set("moduleInfoId", moduleInfoId[i])
						.set("companyCode", companyCode);
				baseCompanyInfoDao.insert(criteriaModuleCompany);
				
				List<ModuleRole> moduleRoleList = baseCompanyInfoDao.queryList(Criteria.create(ModuleRole.class).where
						("isDefaultRole", new Object[]{1}).and("moduleInfoId", new Object[]{moduleInfoId[i]}));
				for(ModuleRole r : moduleRoleList){
					// 给企业管理员设置默认角色
					PortalCompanyRole cr = new PortalCompanyRole();
					cr.setCompanyCode(companyCode);
					cr.setCreateTime(new Date());
					cr.setCreateUser(SpringSecurityUtils.getCurrentUserName());
					cr.setIsDefaultRole(r.getIsDefaultRole());
					cr.setModuleInfoId(r.getModuleInfoId());
					cr.setRoleName(r.getRoleName());
					cr.setRoleRemark(r.getRoleDesc());
					cr.setIsDelete(0);
					Long portalCompanyRoleId = portalCompanyRoleDao.insert(cr);
					
					
					List<ModuleRolePurview> mrrList = portalCompanyRoleDao.queryList(Criteria.create(ModuleRolePurview.class)
							.where("moduleRoleId", new Object[] { r.getModuleRoleId() }));
					for(ModuleRolePurview mr : mrrList){
						PortalCompanyRolePurview pcrr = new PortalCompanyRolePurview();
						pcrr.setCompanyCode(companyCode);
						pcrr.setCreateTime(new Date());
						pcrr.setModulePurviewId(mr.getModulePurviewId());
						pcrr.setPortalCompanyRoleId(portalCompanyRoleId);
						portalCompanyRoleDao.insert(pcrr);
					}
					
					Criteria criteriaPortalCompanyUserRole = Criteria
							.create(PortalCompanyUserRole.class)
							.set("companyCode", companyCode)
							.set("username",baseCompanyInfo.getUsername())
							.set("portalCompanyRoleId",portalCompanyRoleId);
					
					baseCompanyInfoDao.insert(criteriaPortalCompanyUserRole);
				}
			}
		}
		
		
		
		
	}

	/**
	 * 修改代码
	 * {@inheritDoc} 
	 * overridden:
	 * @Date        :      2017年1月6日
	 * @see org.eae.eldf.service.base.BaseCompanyInfoService#updateCompany(org.eae.eldf.entity.base.BaseCompanyInfo)
	*
	 */
	@Override
	public void updateCompany(BaseCompanyInfo c) {
		
		baseCompanyInfoDao.updateCompany(c);
		ValueOperations<String,Object> redisValueObj = objectRedisTemplate.opsForValue();
		redisValueObj.set(CommonContants.CONPANYINFO+c.getCompanyCode(), c);
	}

	@Override
	public List<BaseCompanyInfo> queryAll() {
		// TODO Auto-generated method stub
		return baseCompanyInfoDao.queryCompanyList();
	}
	
}
